package com.admin.education.services.Implements;

import com.admin.education.dataTransferObject.ServicesExcuteResult;
import com.admin.education.dataTransferObject.menus.Mapper.MenuMapper;
import com.admin.education.dataTransferObject.menus.MenusTree;
import com.admin.education.models.Menus;
import com.admin.education.models.QMenus;
import com.admin.education.repositories.MenusRepository;
import com.admin.education.services.Interfaces.IMenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Validated
public class MenusService implements IMenusService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private MenusRepository menusRepository;
    @Override
    public ServicesExcuteResult<MenusTree> queryMenuTree() {
        ServicesExcuteResult<MenusTree> servicesExcuteResult = new ServicesExcuteResult<>();

        QMenus menu = QMenus.menus;
        List<Menus> menus=  this.menusRepository.selectFrom(menu).fetch();

        MenusTree menuTree = this.genernateMenuTree(menus,null);

        servicesExcuteResult.setData(menuTree);
        servicesExcuteResult.setSuccess(true);
        return servicesExcuteResult;
    }

    private MenusTree genernateMenuTree(List<Menus> query,MenusTree menuTree){
        if(null == menuTree) {
            menuTree = new MenusTree();
            menuTree.setMenuCode("");
        }

        String menuCode = menuTree.getMenuCode();
        for(Menus item : query.stream().filter(p->p.getParentMenuCode().equals(menuCode)).collect(Collectors.toList())){
            MenusTree child = menuMapper.mapTo(item);
            menuTree.getChildrens().add(child);

            child=this.genernateMenuTree(query,child);
        }

        return  menuTree;
    }
}
